package com.gonsin.gview.common.controller;


import com.gonsin.base.ResponseResult;
import com.gonsin.base.exceptions.MyException;
import com.gonsin.gview.common.auth.BaseResultCodes;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 控制层基类用于统一处理异常
 * 2019-7-4 create by wsm
 */
@ControllerAdvice
@Slf4j
public abstract class BaseController {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ResponseResult<Void> handleException(Exception e) {
        log.error(e.toString(), e);
        return ResponseResult.simpleResult(500, e.getMessage());
    }

    @ExceptionHandler({MyException.class})
    @ResponseBody
    public ResponseResult<Void> handleMyException(MyException e) {
        return ResponseResult.simpleResult(e.getStatus(), e.getMessage());
    }

    @ExceptionHandler({MissingServletRequestParameterException.class})
    @ResponseBody
    public ResponseResult<Void> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        FormattingTuple ft = MessageFormatter.arrayFormat("请求的接口缺少字段【{}】", new Object[]{e.getParameterName()});
        return ResponseResult.simpleResult(BaseResultCodes.PARAM_ERROR.getValue(), ft.getMessage());
    }

    @ExceptionHandler({MissingPathVariableException.class})
    @ResponseBody
    public ResponseResult<Void> constraintMissingPathVariableException(
            MissingPathVariableException e, HttpServletResponse response) {
        response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
        FormattingTuple ft = MessageFormatter.arrayFormat("缺少参数【{}】", new Object[]{e.getVariableName()});
        return ResponseResult.simpleResult(BaseResultCodes.PARAM_ERROR.getValue(), ft.getMessage());
    }

}

